package com.tubang.logistics.controller.orderV2;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.tubang.common.constant.Constants;
import com.tubang.common.util.*;
import com.tubang.component.entity.AddressEntity;
import com.tubang.component.service.IAddressService;
import com.tubang.component.util.RequestUtil;
import com.tubang.logistics.entity.*;
import com.tubang.logistics.service.*;
import com.tubang.logistics.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单流转 前端控制器
 * </p>
 *
 * @author wsl
 * @since 2017-12-31
 */
@RestController
@RequestMapping("/circulation")
public class OrderCirculationController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IGoodsService goodsService;
    @Resource
    private ILogisticsOrderService logisticsOrderServices;
    @Resource
    private ILogisticsOrderGoodsService logisticsOrderGoodsService;
    @Resource
    private ITransportService transportService;
    @Resource
    private IAddressService addressService;
    @Resource
    private ITruckerOrderService truckerOrderService;
    @Resource
    private IPlatformOrderBiddingService platformOrderBiddingService;
    @Resource
    private ILogisticsBillService logisticsBillService;


    /**
     * 物流公司-货源中心列表
     *
     * @param
     * @return
     */
    @GetMapping(value = "logisticsSuppList")
    public ResultData logisticsSuppList(@RequestParam(required = false) String addrFrom,
                                        @RequestParam(required = false) String addrTo,
                                        @RequestParam(required = false) String num,
                                        @RequestParam(required = false) String companyId,
                                        @RequestParam(required = false, defaultValue = "1") Integer page,
                                        @RequestParam(required = false, defaultValue = "10") Integer rows,
                                        @RequestParam(required = false, defaultValue = "") String userId) {
        try {


            EntityWrapper<LogisticsOrderEntity> logisticsWrapper = new EntityWrapper<>();


            logisticsWrapper.in("status_code", new String[]{Constants.ORDER_STATUS_GRAB, Constants.ORDER_STATUS_BIDDING});

            logisticsWrapper.eq("enable", Constants.DEFAULT_VAULE_ONE);

            if (StringUtils.isNotEmpty(num)) {
                logisticsWrapper.eq("num", num);
            }

            if (StringUtils.isNotEmpty(addrFrom)) {
                logisticsWrapper.like("addr_from", addrFrom);
            }

            if (StringUtils.isNotEmpty(addrTo)) {
                logisticsWrapper.like("addr_to", addrTo);
            }


            logisticsWrapper.or().in("carrier_id", companyId).eq("status_code", Constants.ORDER_STATUS_DESIGNATE);


            int logisticsCount = logisticsOrderServices.selectCount(logisticsWrapper);
            Page<LogisticsOrderEntity> logisticsOrderpPage = logisticsOrderServices.selectPage(new Page(page, rows), logisticsWrapper);
            ArrayList<OrderListVo> logisticsOrderListVos = Lists.newArrayList();
            List<LogisticsOrderEntity> list = logisticsOrderpPage.getRecords();
            for (LogisticsOrderEntity lo : list) {
                try {
                    OrderListVo vo = BeanMapper.map(lo, OrderListVo.class);
                    GoodsEntity goodsEntity = goodsService.selectBaseGoodsByLogisticsOrderId(lo.getId());
                    TransportEntity transportEntity = transportService.selectById(goodsEntity.getTransportId());
                    vo.setGoodsName(goodsEntity.getName());
                    vo.setWeight(String.valueOf(goodsEntity.getWeight()));
                    AddressEntity fAddressEntity = addressService.selectById(transportEntity.getFromUserAddressId());
                    AddressEntity tAddressEntity = addressService.selectById(transportEntity.getToUserAddressId());
                    vo.setAddressFrom(fAddressEntity);
                    vo.setAddresTo(tAddressEntity);
                    vo.setOrderType(Constants.USER_TYPE_OUTSIDE_COMPANY);
                    BeanMapper.copy(transportEntity, vo);
                    vo.setId(lo.getId());
                    vo.setUnloadPlanDateStr(DateFormatUtils.formatDate(transportEntity.getUnloadPlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    vo.setUnloadRealDateStr(DateFormatUtils.formatDate(transportEntity.getUnloadPlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    vo.setTakePlanDateStr(DateFormatUtils.formatDate(transportEntity.getTakePlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    vo.setTakeRealDateStr(DateFormatUtils.formatDate(transportEntity.getTakePlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    PlatformOrderBiddingEntity platformOrderBiddingEntity = platformOrderBiddingService.selectPloByCarrierIdAndOrderId(vo.getId(), companyId);
                    String biddStatusCode = Constants.ORDER_NO_BIDD;
                    String biddStatusCodeDesc = "无竞价记录";
                    if (platformOrderBiddingEntity != null) {
                        biddStatusCode = platformOrderBiddingEntity.getStatusCode();
                        biddStatusCodeDesc = platformOrderBiddingEntity.getStatusCodeDesc();
                    }
                    vo.setBiddStatusCode(biddStatusCode);
                    vo.setBiddStatusCodeDesc(biddStatusCodeDesc);
                    logisticsOrderListVos.add(vo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("数据加工失败，物流公司运单编号为：{}==,,失败原因为{}", lo.getId(), e.getMessage());
                    return ResultData.result(false).setData(e);
                }
            }


            return ResultData.result(true).setData(logisticsOrderListVos).setTotalCount(logisticsCount);
        } catch (Exception e) {
            logger.error("[OrderPlatformController]<== method[platformOrderBillList], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * 物流公司订单调度列表
     *
     * @param
     * @return
     */
    @GetMapping(value = "logisticsDispatchList")
    public ResultData logisticsDispatchList(@RequestParam(required = false) String addrFrom,
                                            @RequestParam(required = false) String addrTo,
                                            @RequestParam(required = false) String goodsName,//货品名称
                                            @RequestParam(required = false) String companyId,
                                            @RequestParam(required = false, defaultValue = "1") Integer page,
                                            @RequestParam(required = false, defaultValue = "10") Integer rows,
                                            @RequestParam(required = false) String userId) {
        try {
            //查询待接单的列表
            EntityWrapper<LogisticsOrderEntity> entityWrapper = new EntityWrapper<LogisticsOrderEntity>();
            entityWrapper.eq("status_code", Constants.ORDER_STATUS_CODE_RELEASE_GOODS);
            entityWrapper.orderBy("create_time", false);
            entityWrapper.eq("enable", Constants.DEFAULT_VAULE_ONE);
            if (StringUtils.isNotEmpty(addrFrom)) {
                entityWrapper.like("addr_from", addrFrom);
            }


            if (StringUtils.isNotEmpty(addrTo)) {
                entityWrapper.like("addr_to", addrTo);
            }

            if (StringUtils.isNotEmpty(goodsName)) {
                entityWrapper.like("goods_name", goodsName);
            }

            if (StringUtils.isNotEmpty(companyId)) {
                entityWrapper.like("carrier_id", companyId);
            }

            if (StringUtils.isNotEmpty(userId)) {
                entityWrapper.like("user_id", userId);
            }


            Page platformOrderPage = logisticsOrderServices.selectPage(new Page(page, rows), entityWrapper);
            List<PlatformOrderEntity> records = platformOrderPage.getRecords();
            List<OrderDispatchListVo> orderDispatchListVos = BeanMapper.mapList(records, OrderDispatchListVo.class);

            for (OrderDispatchListVo orderDispatchListVo : orderDispatchListVos) {
                List<LogisticsOrderGoodsEntity> logisticsOrderGoodsEntities = logisticsOrderGoodsService.selectOrderByOrderId(orderDispatchListVo.getId(), Integer.valueOf(Constants.DEFAULT_VAULE_ONE));
                String orderId = "";
                //补充货物明细
                GoodsEntity goodsBasic = new GoodsEntity();
                GoodsBaseVo goodsBaseVo = new GoodsBaseVo();
                List<GoodsInfoVo> goodsInfoVos = new ArrayList<GoodsInfoVo>();
                for (LogisticsOrderGoodsEntity platformOrderGoodsEntity : logisticsOrderGoodsEntities) {
                    goodsBasic = goodsService.selectBaseGoodsByGoodsId(platformOrderGoodsEntity.getGoodsId());
                    goodsBaseVo = BeanMapper.map(goodsBasic, GoodsBaseVo.class);
                    //重量  名称
                    if (goodsBasic != null) {
                        orderDispatchListVo.setWeight(String.valueOf(goodsBaseVo.getWeight()));
                        orderDispatchListVo.setGoodsName(goodsBaseVo.getName());
                    }
                    GoodsEntity goodsEntity = goodsService.selectById(platformOrderGoodsEntity.getGoodsId());
                    orderId = goodsEntity.getShipperOrderId();
                    String parentId = goodsEntity.getParentId();
                    if (parentId == null || parentId.equals("0")) continue;
                    GoodsInfoVo goodsInfoVo = BeanMapper.map(goodsEntity, GoodsInfoVo.class);
                    goodsInfoVos.add(goodsInfoVo);
                }
                orderDispatchListVo.setGoodsBaseVo(goodsBaseVo);
                orderDispatchListVo.setGoodsInfoVoS(goodsInfoVos);

                //运输详情
                TransportEntity transportEntity = transportService.selectByOrderId(orderId);
                //地址
                if (transportEntity != null) {
                    AddressEntity from = addressService.selectById(transportEntity.getFromUserAddressId());
                    AddressEntity to = addressService.selectById(transportEntity.getToUserAddressId());
                    orderDispatchListVo.setAddressFrom(from);
                    orderDispatchListVo.setAddresTo(to);
                }
                BigDecimal weight = new BigDecimal(0);

                for (GoodsInfoVo goodsEntity : goodsInfoVos) {
                    BigDecimal weight1 = goodsEntity.getWeight();
                    if (weight1 == null) continue;
                    weight = weight.add(weight1);
                }

                orderDispatchListVo.setWeight(String.valueOf(weight));

            }
            int count = logisticsOrderServices.selectCount(entityWrapper);
            return ResultData.result(true).setData(orderDispatchListVos).setTotalCount(count);
        } catch (Exception e) {
            // logger.error("[OrderShipperController]<== method[supplyOrderList], 列表失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * 订单管理列表
     *
     * @param
     * @return
     */
    @GetMapping(value = "orderList")
    public ResultData orderList(@RequestParam(required = false) String addrFrom,
                                @RequestParam(required = false) String addrTo,
                                @RequestParam(required = false) String num,
                                @RequestParam(required = false) String statusCode,//逗号隔开的  需要处理
                                @RequestParam(required = false) String companyId,
                                @RequestParam(required = false) String userId,
                                @RequestParam(required = false, defaultValue = "0") String listType,//0 物流公司-订单管理列表  1,平台子订单列表
                                @RequestParam(required = false, defaultValue = "1") Integer page,
                                @RequestParam(required = false, defaultValue = "10") Integer rows) {
        try {
            EntityWrapper<LogisticsOrderEntity> logisticsWrapper = new EntityWrapper<>();
            //物流公司的订单管理
            if (StringUtils.isNotEmpty(statusCode)) {
                String[] split = statusCode.split(",");
                logisticsWrapper.in("status_code", split);
            }

            if (StringUtils.isNotEmpty(num)) {
                logisticsWrapper.eq("num", num);
            }

            if (StringUtils.isNotEmpty(addrFrom)) {
                logisticsWrapper.like("addr_from", addrFrom);
            }


            if (StringUtils.isNotEmpty(addrTo)) {
                logisticsWrapper.like("addr_to", addrTo);
            }

            if (StringUtils.isNotEmpty(userId)) {
                logisticsWrapper.like("user_id", userId);
            }

            logisticsWrapper.eq("enable", Constants.DEFAULT_VAULE_ONE);
            if (StringUtils.isNotEmpty(companyId)) {
                logisticsWrapper.in("carrier_id", companyId);
                logisticsWrapper.or().eq("create_user_id",companyId);
            }

            int logisticsCount = logisticsOrderServices.selectCount(logisticsWrapper);
            Page<LogisticsOrderEntity> logisticsOrderpPage = logisticsOrderServices.selectPage(new Page(page, rows), logisticsWrapper);
            ArrayList<OrderListVo> logisticsOrderListVos = Lists.newArrayList();
            List<LogisticsOrderEntity> list = logisticsOrderpPage.getRecords();
            for (LogisticsOrderEntity lo : list) {
                try {
                    OrderListVo vo = BeanMapper.map(lo, OrderListVo.class);
                    GoodsEntity goodsEntity = goodsService.selectBaseGoodsByLogisticsOrderId(lo.getId());
                    TransportEntity transportEntity = transportService.selectById(goodsEntity.getTransportId());
                    AddressEntity fAddressEntity = addressService.selectById(transportEntity.getFromUserAddressId());
                    AddressEntity tAddressEntity = addressService.selectById(transportEntity.getToUserAddressId());
                    vo.setAddressFrom(fAddressEntity);
                    vo.setAddresTo(tAddressEntity);
                    vo.setOrderType(Constants.USER_TYPE_OUTSIDE_COMPANY);
                    vo.setWeight(String.valueOf(lo.getGoodsWeight()));
                    logisticsOrderListVos.add(vo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("数据加工失败，物流公司运单编号为：{}==,,失败原因为{}", lo.getId(), e.getMessage());
                    return ResultData.result(false).setData(e);
                }
            }


            return ResultData.result(true).setData(logisticsOrderListVos).setTotalCount(logisticsCount);
        } catch (Exception e) {
            logger.error("[OrderCirculationController]<== method[logisticsOrderList], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * 子订单列表
     *
     * @param statusCode
     * @return
     */
    @GetMapping(value = "orderBillList")
    public ResultData orderBillList(@RequestParam(required = false, defaultValue = "") String statusCode,
                                    @RequestParam(required = false, defaultValue = "") String companyId,
                                    @RequestParam(required = false, defaultValue = "") String userId,
                                    @RequestParam(required = false, defaultValue = "1") Integer page,
                                    @RequestParam(required = false, defaultValue = "10") Integer rows) {
        try {
            logger.info("[picture]==> method[orderList],物流公司运单列表展示 请求数据为：[{}]", statusCode, companyId);
            EntityWrapper<LogisticsOrderEntity> wrapper = new EntityWrapper<>();

            if (StringUtils.isNotEmpty(statusCode)) {
                String[] split = statusCode.split(",");
                wrapper.in("status_code", split);
            }

            if (StringUtils.isNotEmpty(companyId)) {
                wrapper.in("carrier_id", companyId);
            }

            if (StringUtils.isNotEmpty(userId)) {
                wrapper.in("user_id", userId);
            }

            wrapper.eq("enable", Constants.DEFAULT_VAULE_ONE);
            int count = logisticsOrderServices.selectCount(wrapper);
            Page<LogisticsOrderEntity> logisticsOrderpPage = logisticsOrderServices.selectPage(new Page(page, rows), wrapper);

            ArrayList<OrderListVo> orderListVos = Lists.newArrayList();
            List<LogisticsOrderEntity> list = logisticsOrderpPage.getRecords();
            for (LogisticsOrderEntity lo : list) {
                try {
                    OrderListVo vo = BeanMapper.map(lo, OrderListVo.class);
                    GoodsEntity goodsEntity = goodsService.selectBaseGoodsByLogisticsOrderId(lo.getId());
                    TransportEntity transportEntity = transportService.selectById(goodsEntity.getTransportId());
                    vo.setGoodsName(lo.getGoodsName());
                    vo.setWeight(String.valueOf(lo.getGoodsWeight()));
                    vo.setCarriage(lo.getCarriage());
                    AddressEntity fAddressEntity = addressService.selectById(transportEntity.getFromUserAddressId());
                    AddressEntity tAddressEntity = addressService.selectById(transportEntity.getToUserAddressId());
                    vo.setAddressFrom(fAddressEntity);
                    vo.setAddresTo(tAddressEntity);
                    orderListVos.add(vo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("数据加工失败，物流公司运单编号为：{}==,,失败原因为{}", lo.getId(), e.getMessage());
                    return ResultData.result(false).setData(e);
                }
            }
            return ResultData.result(true).setTotalCount(count).setData(orderListVos);
        } catch (Exception e) {
            logger.error("[OrderCirculationController]<== method[orderList], 物流公司运单列表展示失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * 订单调度- 指派 竞价 抢单（调度）
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "logisticsDispatchOrder")
    @Transactional
    public ResultData logisticsDispatchOrder(HttpServletRequest request, HttpServletResponse response) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            OrderDispatchVo orderDispatchVo = GsonQuick.toObject(receivePostJson, OrderDispatchVo.class);
            //物流公司创建订单
            logisticsOrderServices.creatLogisticsOrder(orderDispatchVo);
            List<String> goodsIds = orderDispatchVo.getGoodsIds();
            //更新关系表状态状态
            logisticsOrderGoodsService.upDataOrderGoodsService(goodsIds);
            //更新订单状态
            List<String> orderIds = orderDispatchVo.getOrderIds();
            logisticsOrderServices.updatelogisticsOrderStatus(orderIds, Constants.ORDER_WAITING_PICK_UP_GOODS, "待提货");

            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderCirculationController]<== method[logisticsDispatchOrder], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * @param id
     * @return
     * @Title selectByOrderId
     * @Description 订单 运单 详情
     */
    @GetMapping(value = "selectByOrderId")
    public ResultData selectByOrderId(@RequestParam(required = true) String id) {
        try {
            OrderInfoVo orderbInfoVo = new OrderInfoVo();
            LogisticsOrderEntity logisticsOrderEntity = logisticsOrderServices.selectById(id);
            BeanMapper.copy(logisticsOrderEntity, orderbInfoVo);
            List<LogisticsOrderGoodsEntity> logisticsOrderGoodsEntities = logisticsOrderGoodsService.selectOrderByOrderId(id, null);
            String orderId = "";
            //补充货物明细
            GoodsEntity goodsBasic = new GoodsEntity();
            GoodsBaseVo goodsBaseVo = new GoodsBaseVo();
            for (LogisticsOrderGoodsEntity logisticsOrderGoodsEntity : logisticsOrderGoodsEntities) {
                goodsBasic = goodsService.selectBaseGoodsByGoodsId(logisticsOrderGoodsEntity.getGoodsId());
                goodsBaseVo = BeanMapper.map(goodsBasic, GoodsBaseVo.class);
                orderId = goodsBasic.getShipperOrderId();
            }
            List<GoodsEntity> goodsEntities = goodsService.selectGoodssByLogisticsOrderId(id, null);
            List<GoodsInfoVo> goodsInfoVos = BeanMapper.mapList(goodsEntities, GoodsInfoVo.class);
            orderbInfoVo.setGoodsBaseVo(goodsBaseVo);
            orderbInfoVo.setGoodsInfoVoS(goodsInfoVos);
            //运输详情
            TransportEntity transportEntity = transportService.selectByOrderId(orderId);
            //地址
            if (transportEntity != null) {
                AddressEntity from = addressService.selectById(transportEntity.getFromUserAddressId());
                AddressEntity to = addressService.selectById(transportEntity.getToUserAddressId());
                orderbInfoVo.setAddressFrom(from);
                orderbInfoVo.setAddresTo(to);
                orderbInfoVo.setUnloadPlanDateStr(DateFormatUtils.formatDate(transportEntity.getUnloadPlanDate(), "yyyy-MM-dd HH:mm:ss"));
                orderbInfoVo.setTakePlanDateStr(DateFormatUtils.formatDate(transportEntity.getTakePlanDate(), "yyyy-MM-dd HH:mm:ss"));
                BeanMapper.copy(transportEntity, orderbInfoVo);
            }

            //查询商品在物流公司的运单数据

            //查询商品在平台的运单数据
            List<OrderbillSimpleVo> orderbillSimpleVos = orderbInfoVo.getOrderbillSimpleVos();
            List<String> numbs = new ArrayList<String>();
            for (GoodsEntity goods : goodsEntities) {
                LogisticsOrderGoodsEntity logisticsOrderGoodsEntity = logisticsOrderGoodsService.selectOrderByGoodsId(goods.getId(), null);
                if (logisticsOrderGoodsEntity == null) continue;
                LogisticsOrderEntity logisticsOrder = logisticsOrderServices.selectById(logisticsOrderGoodsEntity.getLogisticsOrderId());
                if (logisticsOrder == null) continue;
                //同一订单商品
                if (numbs.contains(logisticsOrder.getId())) continue;
                OrderbillSimpleVo orderbillSimpleVo = BeanMapper.map(logisticsOrder, OrderbillSimpleVo.class);
                orderbillSimpleVos.add(orderbillSimpleVo);
                numbs.add(logisticsOrder.getId());
            }
            return ResultData.result(true).setData(orderbInfoVo);
        } catch (Exception e) {
            logger.error("[OrderShipperController]<== method[supplyOrderBillInfo], 查询详情 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }


    }


    /**
     * 接单 驳回
     *
     * @param
     * @return
     */
    @PostMapping(value = "logisticsChoiceOrder")
    public ResultData logisticsChoiceOrder(HttpServletRequest request) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            OrderBiddingVo platformOrderBiddingVo = GsonQuick.toObject(receivePostJson, OrderBiddingVo.class);

            Date now = new Date();
            //公司指派来的单 (接单,驳回)
            Integer status = platformOrderBiddingVo.getStatus();

            if (Constants.ORDER_STATUS_CODE_RELEASE_GOODS == status) {
                //接单
                LogisticsOrderEntity logisticsOrderEntity = logisticsOrderServices.selectById(platformOrderBiddingVo.getOrderId());
                if (logisticsOrderEntity == null) ResultData.result(true);
                logisticsOrderEntity.setStatusCode(String.valueOf(status));
                logisticsOrderEntity.setStatusCodeDesc(platformOrderBiddingVo.getStatusCodeDesc());
                logisticsOrderEntity.setCarrierId(platformOrderBiddingVo.getCarrierId());
                logisticsOrderEntity.setCarrierName(platformOrderBiddingVo.getCarrierName());
                logisticsOrderEntity.setCarrierMobile(platformOrderBiddingVo.getCarrierMobile());
                logisticsOrderEntity.setRemarks(platformOrderBiddingVo.getRemarks());
                Double carriage = logisticsOrderEntity.getCarriage();
                if (carriage != null && carriage > 0) {
                    logisticsOrderEntity.setCarriage(carriage);
                }
                logisticsOrderEntity.setUpdateTime(now);
                platformOrderBiddingVo.setUserId(logisticsOrderEntity.getUserId());
                logisticsOrderServices.insertOrUpdate(logisticsOrderEntity);
            }


            if (Constants.ORDER_STATUS_REFUSE_ORDER.equals(String.valueOf(status))) {
                //拒绝接单
                LogisticsOrderEntity logisticsOrderEntity = logisticsOrderServices.selectById(platformOrderBiddingVo.getOrderId());
                if (logisticsOrderEntity == null) ResultData.result(true);
                logisticsOrderEntity.setStatusCode(String.valueOf(status));
                logisticsOrderEntity.setStatusCodeDesc(platformOrderBiddingVo.getStatusCodeDesc());
                logisticsOrderEntity.setCarrierId(platformOrderBiddingVo.getCarrierId());
                logisticsOrderEntity.setCarrierName(platformOrderBiddingVo.getCarrierName());
                logisticsOrderEntity.setCarrierMobile(platformOrderBiddingVo.getCarrierMobile());
                logisticsOrderEntity.setRemarks(platformOrderBiddingVo.getRemarks());
                Double carriage = logisticsOrderEntity.getCarriage();
                if (carriage != null && carriage > 0) {
                    logisticsOrderEntity.setCarriage(carriage);
                }
                logisticsOrderEntity.setUpdateTime(now);
                platformOrderBiddingVo.setUserId(logisticsOrderEntity.getUserId());
                //判断是否是直接创建的订单
                if (StringUtils.equals(logisticsOrderEntity.getCreateUserId()
                        , logisticsOrderEntity.getUserId())) {
                    //是直接创建 进行续选

                } else {
                    logisticsOrderServices.orderRobackStatuscode(logisticsOrderEntity);
                }
                logisticsOrderServices.insertOrUpdate(logisticsOrderEntity);

            }
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderCirculationController]<== method[platformChoiceOrder], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * 竞价-终选  抢单-终选
     * <p>
     * 1,平台订单精选后 选择公司  司机   2, 公司, 司机 抢单
     *
     * @param
     * @return
     */
    @PostMapping(value = "logisticsConfirmOrder")
    public ResultData logisticsConfirmOrder(HttpServletRequest request) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            OrderBiddingVo platformOrderBiddingVo = GsonQuick.toObject(receivePostJson, OrderBiddingVo.class);

            Date now = new Date();
            //更新主单状态
            String orderType = platformOrderBiddingVo.getOrderType();
            LogisticsOrderEntity logisticsOrderEntity = logisticsOrderServices.selectById(platformOrderBiddingVo.getOrderId());
            if (logisticsOrderEntity != null) {
                logisticsOrderEntity.setStatusCode(String.valueOf(Constants.ORDER_STATUS_CODE_RELEASE_GOODS));
                logisticsOrderEntity.setStatusCodeDesc("待调度");
                logisticsOrderEntity.setCarrierId(platformOrderBiddingVo.getCarrierId());
                logisticsOrderEntity.setCarrierName(platformOrderBiddingVo.getCarrierName());
                logisticsOrderEntity.setCarrierMobile(platformOrderBiddingVo.getCarrierMobile());
                logisticsOrderEntity.setRemarks(platformOrderBiddingVo.getRemarks());
                Double carriage = logisticsOrderEntity.getCarriage();
                if (carriage != null) {
                    logisticsOrderEntity.setCarriage(carriage);
                }
                logisticsOrderEntity.setUpdateTime(now);
                logisticsOrderServices.insertOrUpdate(logisticsOrderEntity);

                platformOrderBiddingVo.setUserId(logisticsOrderEntity.getUserId());
                //司机 抢单 接单 竞价最终选择
                if (Constants.USER_TYPE_INSIDE_DRIVER.equals(String.valueOf(orderType))) {
                    //司机指派单 直接生成运单
                    platformOrderBiddingVo.setGoodsWeight(logisticsOrderEntity.getGoodsWeight());
                    platformOrderBiddingVo.setGoodsName(logisticsOrderEntity.getGoodsName());
                    platformOrderBiddingVo.setCarriage(logisticsOrderEntity.getCarriage());
                    platformOrderBiddingVo.setAmount(logisticsOrderEntity.getAmountDeal());
                    truckerOrderService.creatTruckerOrderBeforePlatformOrder(platformOrderBiddingVo);
                    return ResultData.result(true);
                }

                //如果竞价id 更新竞价状态
                String orderBiddId = platformOrderBiddingVo.getOrderBiddId();
                if (orderBiddId == null) {
                    return ResultData.result(true);
                }

                PlatformOrderBiddingEntity platformOrderBiddingEntity = platformOrderBiddingService.selectById(orderBiddId);
                if (platformOrderBiddingEntity == null) {
                    return ResultData.result(true);
                }
                platformOrderBiddingEntity.setStatusCode(Constants.ORDER_BIDD_OK);
                platformOrderBiddingEntity.setStatusCodeDesc("竞价成功");
                platformOrderBiddingEntity.setUpdateTime(now);
                platformOrderBiddingService.insertOrUpdate(platformOrderBiddingEntity);
            }

            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderCirculationController]<== method[logisticsConfirmOrder], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * 物流公司改价
     *
     * @param
     * @return
     */
    @PostMapping(value = "logisticsOrderChangeCarriage")
    public ResultData logisticsOrderChangeCarriage(HttpServletRequest request) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            PlatformOrderChangeCarriageVo platformOrderChangeCarriageVo = GsonQuick.toObject(receivePostJson, PlatformOrderChangeCarriageVo.class);
            Date now = new Date();
            LogisticsOrderEntity logisticsOrderEntity = logisticsOrderServices.selectById(platformOrderChangeCarriageVo.getOrderId());
            if (logisticsOrderEntity == null) ResultData.result(true);
            logisticsOrderEntity.setCarriageDeal(platformOrderChangeCarriageVo.getCarriage());
            Double carriage = logisticsOrderEntity.getCarriage();
            if (carriage <= 0) {
                carriage = 1d;
            }
            double a = logisticsOrderEntity.getAmount() / carriage;
            logisticsOrderEntity.setAmountDeal(platformOrderChangeCarriageVo.getCarriage() * a);
            logisticsOrderEntity.setUpdateTime(now);
            logisticsOrderServices.insertOrUpdate(logisticsOrderEntity);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderCirculationController]<== method[logisticsOrderChangeCarriage], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * @param request
     * @param response 104 105
     * @return ResultData 返回类型
     * @throws
     * @Title logisticsBargain
     * @Description 审核 订单 子订单
     */
    @PostMapping(value = "logisticsOrderAudit")
    public ResultData logisticsOrderAudit(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        TruckerBackVo truckerBackVo = GsonQuick.toObject(receivePostJson, TruckerBackVo.class);
        try {

            if (StringUtils.isBlank(truckerBackVo.getId())) {
                return ResultData.result(false).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC);
            }
            LogisticsOrderEntity logisticsOrderEntity = logisticsOrderServices.selectById(truckerBackVo.getId());
            //判断是否审核通过
            if (!StringUtils.equals(Constants.ORDER_WAIT_FOR_CONFIRMATION, logisticsOrderEntity.getStatusCode())) {
                return ResultData.result(false).setCode(MsgCode.ORDER_DATA_ERROR).setMsg(MsgCode.ORDER_DATA_ERROR_DESC);
            }
            logisticsOrderEntity.setStatusCode(truckerBackVo.getStatusCode());
            logisticsOrderEntity.setStatusCodeDesc(truckerBackVo.getStatusCodeDesc());
            logisticsOrderServices.insertOrUpdate(logisticsOrderEntity);
            //更新与此订单中所以货品相关的状态
            List<LogisticsOrderGoodsEntity> logisticsOrderGoodsEntities = logisticsOrderGoodsService.selectOrderByOrderId(truckerBackVo.getId(), null);
            //生成货品id集合
            List<String> goodsIdlist = new ArrayList<String>();
            for (LogisticsOrderGoodsEntity logisticsOrderGoodsEntity : logisticsOrderGoodsEntities) {
                goodsIdlist.add(logisticsOrderGoodsEntity.getGoodsId());
            }
            //更新相关订单状态
            //logisticsOrderServices.updateLogisticsOrderStatusAdmByGoodsIds(goodsIdlist, Constants.ORDER_IN_TRANSIT, "运输中");

            if (truckerBackVo.getStatusCode() != null && truckerBackVo.getStatusCode().equals(Constants.ORDER_HAVA_COMPLETED)) {
                //审核通过生成账单
                LogisticsBill logisticsBill = new LogisticsBill();
                BeanMapper.copy(logisticsOrderEntity, logisticsBill);
                logisticsBill.setId(null);
                logisticsBill.setNum(IdGenerator.INSTANCE.nextId());
                logisticsBill.setOrderNum(logisticsOrderEntity.getNum());
                logisticsBill.setOrderId(logisticsOrderEntity.getId());
                logisticsBill.setFinishTime(logisticsOrderEntity.getUpdateTime());
                logisticsBill.setStatusCode(null);
                logisticsBillService.insertOrUpdate(logisticsBill);
            }


            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[logisticsTakeGoods],上传提货单，并确认提货 失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


}
